package com.iteaj.network.codec.adapter;

import com.iteaj.network.AbstractMessage;
import com.iteaj.network.codec.SocketMessageDecoder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @see io.netty.channel.ChannelHandler.Sharable 如果是线程安全可以使用
 */
public class SimpleChannelDecoderAdapter extends SimpleChannelInboundHandler<ByteBuf> {

    private SocketMessageDecoder socketMessageDecoder;

    public SimpleChannelDecoderAdapter(SocketMessageDecoder socketMessageDecoder) {
        this.socketMessageDecoder = socketMessageDecoder;
    }

    public SimpleChannelDecoderAdapter(boolean autoRelease, SocketMessageDecoder socketMessageDecoder) {
        super(autoRelease);
        this.socketMessageDecoder = socketMessageDecoder;
    }

    public SimpleChannelDecoderAdapter(Class<? extends ByteBuf> inboundMessageType, SocketMessageDecoder socketMessageDecoder) {
        super(inboundMessageType);
        this.socketMessageDecoder = socketMessageDecoder;
    }

    public SimpleChannelDecoderAdapter(Class<? extends ByteBuf> inboundMessageType, boolean autoRelease, SocketMessageDecoder socketMessageDecoder) {
        super(inboundMessageType, autoRelease);
        this.socketMessageDecoder = socketMessageDecoder;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        final AbstractMessage proxy = socketMessageDecoder.proxy(ctx, msg);
        if(proxy != null) {
            ctx.fireChannelRead(proxy);
        }
    }
}
